'use strict';

module.exports = (app) => {
  class NewsService extends app.Service {
    async create() {
      const { app, ctx } = this;
      const { News } = app.model.Tables.Web;
      const data = ctx.request.body;

      const res = await News.create({
        cover: data.cover,
        title: data.title,
        sketch: data.sketch,
        content: data.content,
        projectId: ctx.adminInfo.project_id,
      });

      return res;
    }

    async delete() {
      const { app, ctx } = this;
      const { News } = app.model.Tables.Web;
      const { id } = ctx.params;
      const res = await News.destroy({
        where: {
          id,
          projectId: ctx.adminInfo.project_id,
        },
      });
      if (res) {
        return '删除成功';
      }
      return 'id不存在,删除失败';
    }

    async update() {
      const { app, ctx } = this;
      const { News } = app.model.Tables.Web;
      const data = ctx.request.body;
      const res = await News.update(
        {
          cover: data.cover,
          title: data.title,
          sketch: data.sketch,
          content: data.content,
        },
        {
          where: {
            id: data.id,
            projectId: ctx.adminInfo.project_id,
          },
        }
      );
      if (res[0]) {
        return '修改成功';
      }
      return 'id不存在,修改失败';
    }

    async getAll() {
      const { app, ctx } = this;
      const { News } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await News.findAndCountAll({
        where: {
          projectId: data.projectId || ctx.adminInfo.project_id,
        },
        limit: Number(data.limit) || 10,
        offset: Number(data.offset) || 0,
      });

      return res;
    }

    async getById() {
      const { app, ctx } = this;
      const { News } = app.model.Tables.Web;
      const data = ctx.query;

      const res = await News.findOne({
        where: {
          id: data.id,
        },
      });

      if (res) {
        // 新闻浏览次数自增1
        await News.findByPk(data.id).then(function (News) {
          News.increment('readCount').then(function () {
            console.log('success');
          });
        });
      }
      return res;
    }
  }

  return NewsService;
};
